document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const scoreElement = document.getElementById('score');
    const gameOverElement = document.getElementById('gameOver');
    const finalScoreElement = document.getElementById('finalScore');
    const startBtn = document.getElementById('startBtn');
    const pauseBtn = document.getElementById('pauseBtn');
    const resetBtn = document.getElementById('resetBtn');
    const playAgainBtn = document.getElementById('playAgainBtn');

    // 游戏设置
    const gridSize = 20;
    const tileCount = canvas.width / gridSize;
    let snake = [{ x: 10, y: 10 }];
    let food = { x: 15, y: 15 };
    let dx = 1; // x方向速度
    let dy = 0; // y方向速度
    let score = 0;
    let gameLoopId;
    let isPaused = false;
    let isGameOver = false;

    // 初始化游戏
    function init() {
        snake = [{ x: 10, y: 10 }];
        dx = 1;
        dy = 0;
        score = 0;
        scoreElement.textContent = score;
        gameOverElement.style.display = 'none';
        isGameOver = false;
        isPaused = false;
        spawnFood();
        gameLoop();
    }

    // 生成食物
    function spawnFood() {
        food.x = Math.floor(Math.random() * tileCount);
        food.y = Math.floor(Math.random() * tileCount);

        // 确保食物不会出现在蛇身上
        const onSnake = snake.some(segment => segment.x === food.x && segment.y === food.y);
        if (onSnake) {
            spawnFood();
        }
    }

    // 绘制游戏元素
    function draw() {
        // 清空画布
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制蛇
        snake.forEach((segment, index) => {
            // 蛇头使用不同颜色
            ctx.fillStyle = index === 0 ? '#4CAF50' : '#8BC34A';
            ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 1, gridSize - 1);
        });

        // 绘制食物
        ctx.fillStyle = '#FF5722';
        ctx.beginPath();
        ctx.arc(
            food.x * gridSize + gridSize / 2,
            food.y * gridSize + gridSize / 2,
            gridSize / 2 - 1,
            0,
            Math.PI * 2
        );
        ctx.fill();
    }

    // 更新游戏状态
    function update() {
        if (isPaused || isGameOver) return;

        // 移动蛇
        const head = { x: snake[0].x + dx, y: snake[0].y + dy };
        snake.unshift(head);

        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            score += 10;
            scoreElement.textContent = score;
            spawnFood();
        } else {
            // 如果没吃到食物，移除尾部
            snake.pop();
        }

        // 检查碰撞
        checkCollisions();
    }

    // 检查碰撞
    function checkCollisions() {
        const head = snake[0];

        // 墙壁碰撞
        if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
            gameOver();
            return;
        }

        // 自碰撞
        for (let i = 1; i < snake.length; i++) {
            if (head.x === snake[i].x && head.y === snake[i].y) {
                gameOver();
                return;
            }
        }
    }

    // 游戏结束
    function gameOver() {
        isGameOver = true;
        cancelAnimationFrame(gameLoopId);
        finalScoreElement.textContent = score;
        gameOverElement.style.display = 'block';
    }

    // 游戏循环
    function gameLoop() {
        update();
        draw();
        gameLoopId = requestAnimationFrame(gameLoop);
    }

    // 键盘控制
    document.addEventListener('keydown', (e) => {
        const LEFT_KEY = 37;
        const RIGHT_KEY = 39;
        const UP_KEY = 38;
        const DOWN_KEY = 40;

        const keyPressed = e.keyCode;
        const goingUp = dy === -1;
        const goingDown = dy === 1;
        const goingRight = dx === 1;
        const goingLeft = dx === -1;

        if (keyPressed === LEFT_KEY && !goingRight) {
            dx = -1;
            dy = 0;
        }

        if (keyPressed === UP_KEY && !goingDown) {
            dx = 0;
            dy = -1;
        }

        if (keyPressed === RIGHT_KEY && !goingLeft) {
            dx = 1;
            dy = 0;
        }

        if (keyPressed === DOWN_KEY && !goingUp) {
            dx = 0;
            dy = 1;
        }
    });

    // 按钮事件
    startBtn.addEventListener('click', () => {
        if (isGameOver) {
            init();
        } else if (isPaused) {
            isPaused = false;
            gameLoop();
        }
    });

    pauseBtn.addEventListener('click', () => {
        if (!isGameOver) {
            isPaused = true;
            cancelAnimationFrame(gameLoopId);
        }
    });

    resetBtn.addEventListener('click', init);
    playAgainBtn.addEventListener('click', init);

    // 初始化游戏
    init();
});